# Author: Mr.Xu
# @Time : 2019/12/3 21:57
from django.core.cache import cache
from django.db.models import F

from .celery import app
from home import models as home_models, serializers as home_serializers
from libs.tx_sms import send_sms
from utils.response import APIResponse
from video import models as video_models, serializers as video_serializers
from django.conf import settings

'''定时任务'''
@app.task
def update_banner_cache():
    '''定时更新轮播图'''
    # 查询数据库
    banner_query = home_models.Banner.objects.filter(is_show=True).order_by("-order")[:settings.BANNER_COUNT]
    # 序列化数据对象得到序列化后的json列表
    banner_list = home_serializers.BannerModelSerializer(banner_query, many=True).data
    # 设置缓存,走的是默认项目配置的缓存数据库
    cache.set('banner_list', banner_list)


@app.task
def update_ranking_cache():
    '''定时更新排名'''
    # 更新热播
    queryset = video_models.Video.objects.filter(is_show=True).order_by("-heat").all()[:settings.RANKING_COUNT]
    heat_list = video_serializers.LeaderboardSerializer(queryset, many=True).data
    cache.set('heat_list', heat_list)

    # 更新热搜
    queryset = video_models.Video.objects.filter(is_show=True).order_by("-search").all()[:settings.RANKING_COUNT]
    search_list = video_serializers.LeaderboardSerializer(queryset, many=True).data
    cache.set('search_list', search_list)


@app.task
def update_recommend_data():
    '''定时更新推荐视频'''
    home_models.Recommend.objects.all().delete()
    obj_set = []
    cat_list = video_models.Category.objects.all()
    # cat_list = list(cat_list)
    '''更新推荐视频表'''
    for cat in cat_list:
        obj_list = video_models.Video.objects.filter(category__pk=cat.pk).all().order_by("-heat")[:5]
        i = settings.RECOMMEND_COUNT
        for obj in obj_list:
            if obj.sections == obj.pub_sections:
                if obj.category.name == "电影":
                    status = "正片"
                elif obj.category.name == "电视剧":
                    status = f"{obj.sections}集全"
                elif obj.category.name == "综艺":
                    status = f"{obj.sections}期全"
                elif obj.category.name == "动漫":
                    status = f"{obj.sections}话全"
                elif obj.category.name == "纪录片":
                    status = f"{obj.sections}集全"
                else:
                    status = f"{obj.sections}集全"
            else:
                if obj.category.name == "电视剧":
                    status = f"更新至{obj.pub_sections}集"
                elif obj.category.name == "综艺":
                    status = f"更新至{obj.pub_sections}期"
                elif obj.category.name == "动漫":
                    status = f"更新至{obj.pub_sections}话"
                elif obj.category.name == "纪录片":
                    status = f"更新至{obj.pub_sections}集"
                else:
                    status = f"更新至{obj.pub_sections}集"
            obj_set.append(home_models.Recommend(
                title=obj.title,
                score=obj.score,
                image=obj.image,
                heat=obj.heat,
                order=i,
                is_free=obj.is_free,
                category_id=cat.pk,
                video_id=obj.pk,
                status=status,
            ))
            i -= 1
    home_models.Recommend.objects.bulk_create(obj_set)

    '''更新推荐视频缓存'''
    # 查询所有分类
    category_list = video_models.Category.objects.all()
    recommend_video_dic = {}
    # 根据分类取推荐表推荐个数的记录并进行序列化
    for category in category_list:
        queryset = home_models.Recommend.objects.filter(is_show=True, category_id=category.pk).order_by("-order")[
                   :settings.RECOMMEND_COUNT]
        recommend_video_dic[category.name] = home_serializers.RecommendModelSerializer(queryset, many=True).data
    cache.set('recommend_video_dic', recommend_video_dic)


'''立即任务'''
# 需要手机号、验证码、过期时间(min)
@app.task
def send_sms_task(mobile, code, exp):
    result = send_sms(mobile, code, exp)
    if not result:
        return APIResponse(1, "验证码发送失败")


# 更新热度
@app.task
def update_video_heat(video_pk):
    obj = video_models.Video.objects.filter(pk=video_pk).first()
    if obj:
        obj.heat += 1
        obj.save()


# 更新搜索
@app.task
def update_video_search(objs_data):
    for obj_data in objs_data:
        pk = obj_data.get("id")
        # 查询数据库
        video_models.Video.objects.filter(pk=pk).update(search=F("search") + 1)


# 更新播放视频记录
# @app.task
# def update_video_record(user_obj, data):
#     obj = video_models.Record.objects.filter(
#         user=user_obj,
#         video_section_id=data.get("section_id")
#     ).first()
#     # 如果有记录
#     if not obj:
#         video_models.Record.objects.create(
#             user=user_obj,
#             video_section_id=data.get("section_id"),
#             play_time=data.get("play_time")
#         )
#     else:
#         # 如果没有记录。就判断播放时间然后取更新
#         if data.get("play_time") > obj.play_time:
#             obj.play_time = data.get("play_time")
#             obj.save()